/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package encaps.security;

import encaps.utils.AbstractCache;
import encaps.entities.Grant;
import encaps.entities.Role;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.sql.DataSource;
import encaps.utils.DatabaseUtil;


public class RoleCache extends AbstractCache<String, Role> {

    private DataSource dataSource;
    private RoleManager rm;

    public RoleCache() throws DataAccessException {
        try {
            dataSource = DatabaseUtil.getDataSource();
            rm = new RoleManager();
        } catch(NamingException ex) {
            throw new DataAccessException("Cannot find DataSource object", ex);
        }
    }
/*@Override
    protected void loadObjectToCache(String requestedRole) throws DataAccessException
    {
        try {
            Role r = rm.loadRole(requestedRole);
            putIntoCache(r.getRoleName(), r);
        } catch (SQLException ex) {
            Logger.getLogger(RoleCache.class.getName()).log(Level.SEVERE, null, ex);
        }
            
        
    }*/
    @Override
    protected void loadObjectToCache(String requestedRole) throws DataAccessException {
        Connection conn = null;
        PreparedStatement rolePS = null;
        PreparedStatement grantPS = null;
        try {
            conn = dataSource.getConnection();
            rolePS = conn.prepareStatement("SELECT name, grant_name FROM role JOIN role_grant ON role.name = role_grant.role_name WHERE name = ?");
            rolePS.setString(1, requestedRole);
            ResultSet rs = rolePS.executeQuery();
            if(!rs.next()) {
                throw new DataAccessException("No such role: " + requestedRole);
            }
            String roleName = rs.getString("name");
            Role role = new Role(roleName);
            do {
                String grantName = rs.getString("grant_name");
                Grant grant = new Grant(grantName);
                role.addGrant(grant);
            } while(rs.next());
            
            putIntoCache(roleName, role);
        } catch(SQLException ex) {
            throw new DataAccessException("Cannot load object from database", ex);
        } finally {
            DatabaseUtil.closeConnection(conn, rolePS);
            DatabaseUtil.closeConnection(null, grantPS);
        }
    }

}
